<template>
  <div>
    给<span style="color: red">{{ role.roleName }}</span>分配权限
    <ul id="basicTree" class="ztree"></ul>

    <el-button type="warning" @click="doDistPermToRole">分配权限</el-button>
  </div>
</template>

<script>
import { findAll as findAllPermissions } from "@/api/permission/index.js";
import { findOne as findOneRole ,distPermToRole} from "@/api/role/index.js";

export default {
  mounted() {
    findAllPermissions().then((r) => {
      this.initTree(r);

    }).then(()=>{
      findOneRole(this.$route.params.roleId).then((r) => {
        this.role = r.data;
        this.checkPermission();
      });
    })
  },
  data() {
    return {
      role: {},
    };
  },
  methods: {
    initTree(resp) {
      // 设置参数
      let settings = {
        check: {
          enable: true,
        },
        data: {
          key: {
            name: "permissionName",
          },
          simpleData: {
            enable: true, // 启用简单树
            idKey: "permissionId",
            pIdKey: "parentId",
          },
        },
      };

      // 设置树的数据
      let nodes = resp.data;

      // 初始化树
      $.fn.zTree.init($("#basicTree"), settings, nodes);
      var treeObj = $.fn.zTree.getZTreeObj("basicTree");
      treeObj.expandAll(true);
    },
    checkPermission() {
      //获取树中的所有节点
      var treeObj = $.fn.zTree.getZTreeObj("basicTree");
      var nodes = treeObj.getNodes();
      var flatNodes = treeObj.transformToArray(nodes);

      let permissionIds = this.role.permissions.map(p=>p.permissionId);

      let targetPermissions = flatNodes.filter(p => permissionIds.includes(p.permissionId));

      targetPermissions.forEach(n=>{
        treeObj.checkNode(n, true, false);
      })
    },
    doDistPermToRole(){
      let roleId = this.role.roleId;
      var treeObj = $.fn.zTree.getZTreeObj("basicTree");
      var checkedNodes = treeObj.getCheckedNodes(true);
      
      let checkedPermissionIds = checkedNodes.map(p=> p.permissionId);
      distPermToRole(roleId,checkedPermissionIds).then(r=>{
        if(r.code == 200){
          this.$message.success(r.msg);
          return;
        }
        this.$message.error(r.msg);
      })

    }
  },
};
</script>

<style></style>
